package com.czk.zookeeper.zookeepercli.watcher;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/1/4 20:07
 */
public class ZkConnectionWatcher implements Watcher {
    /**
     * 计数器对象
     */
    static CountDownLatch countDownLatch = new CountDownLatch(1);
    /**
     * 连接对象
     */
    static ZooKeeper zooKeeper;

    public static void main(String[] args) {
        try {
            zooKeeper = new ZooKeeper("192.168.25.133:2181", 10000, new ZkConnectionWatcher());
            // 线程等待
            countDownLatch.await();
            // 会话id
            System.out.println(zooKeeper.getSessionId());
            // 线程休眠
            TimeUnit.SECONDS.sleep(5);
            System.out.println("结束");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        try {
            // 捕获事件类型
            if (watchedEvent.getType() == Event.EventType.None) {
                if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
                    //
                    System.out.println("连接成功");
                    // 计数器减一
                    countDownLatch.countDown();
                }
                if (watchedEvent.getState() == Event.KeeperState.Disconnected) {
                    System.out.println("断开连接");
                }
                if (watchedEvent.getState() == Event.KeeperState.Expired) {
                    System.out.println("会话超时");
                }
                if (watchedEvent.getState() == Event.KeeperState.AuthFailed) {
                    System.out.println("认证失败");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
